import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    flowers: [], // 花卉列表
    cart: JSON.parse(localStorage.getItem("cart")) || [], // 从localStorage加载购物车
    user: null, // 用户信息
    categories: [
      { id: 1, name: "降噪耳机" },
      { id: 2, name: "HiFi耳机" },
      { id: 3, name: "蓝牙耳机" },
      { id: 4, name: "游戏耳机" },
      { id: 5, name: "真无线耳机" },
    ], // 商品分类
    // 模拟用户数据库
    users: [], // 允许任何账号密码登录，不从localStorage加载，也不包含默认admin用户
    userOrders: JSON.parse(localStorage.getItem("userOrders")) || [], // 从localStorage加载用户订单
  },
  getters: {
    cartTotal: (state) => {
      return state.cart.reduce(
        (total, item) => total + item.price * item.quantity,
        0
      );
    },
    cartCount: (state) => {
      return state.cart.reduce((count, item) => count + item.quantity, 0);
    },
  },
  mutations: {
    setFlowers(state, flowers) {
      state.flowers = flowers;
    },
    addToCart(state, flower) {
      const existingItem = state.cart.find((item) => item.id === flower.id);
      if (existingItem) {
        existingItem.quantity += flower.quantity || 1;
      } else {
        state.cart.push({ ...flower, quantity: flower.quantity || 1 });
      }
    },
    removeFromCart(state, item) {
      const index = state.cart.findIndex((cartItem) => cartItem.id === item.id);
      if (index > -1) {
        state.cart.splice(index, 1);
      }
    },
    setUser(state, user) {
      state.user = user;
      // 确保保存到本地存储，以便路由守卫检查登录状态
      if (user) {
        localStorage.setItem("user", JSON.stringify(user));
      } else {
        localStorage.removeItem("user");
      }
    },
    addUser(state, user) {
      state.users.push(user);
      // 注册用户仍然保存到本地存储
      localStorage.setItem("registeredUsers", JSON.stringify(state.users));
    },
    addOrder(state, order) {
      state.userOrders.push(order);
      // 确保保存到本地存储，以便用户订单持久化
      localStorage.setItem("userOrders", JSON.stringify(state.userOrders));
    },
    addToCartWithQuantity(state, { flower, quantity }) {
      const existingItem = state.cart.find((item) => item.id === flower.id);
      if (existingItem) {
        existingItem.quantity += quantity;
      } else {
        state.cart.push({ ...flower, quantity });
      }
    },
    setCartItemSelected(state, { itemId, selected }) {
      const itemIndex = state.cart.findIndex(item => item.id === itemId);
      if (itemIndex > -1) {
        // Create a new object to ensure reactivity update
        const updatedItem = { ...state.cart[itemIndex], selected };
        state.cart.splice(itemIndex, 1, updatedItem);
      }
    },
    // Mutation to set the selected state of all cart items
    setAllCartItemsSelected(state, selected) {
      state.cart = state.cart.map(item => ({ ...item, selected }));
    },
    // New mutation to set the quantity of a single cart item
    setCartItemQuantity(state, { itemId, quantity }) {
      const item = state.cart.find(item => item.id === itemId);
      if (item) {
        // Use Vue.set to ensure reactivity if the property wasn't already reactive
        Vue.set(item, 'quantity', quantity);
      }
    },
    // Mutation to clear the cart or set its content
    setCart(state, newCart) {
      state.cart = newCart;
      // 确保保存购物车到本地存储
      localStorage.setItem("cart", JSON.stringify(state.cart));
    }
  },
  actions: {
    async fetchFlowers({ commit }) {
      const flowers = [
        {
          id: 1,
          name: "索尼 WH-1000XM4",
          price: 2999,
          image: require("@/assets/images/headphone/sony-wh1000xm4.jpg"),
          description: "旗舰级降噪耳机，舒适佩戴，超长续航。",
          tags: ["热销", "旗舰"],
          stock: 100,
          categoryId: 1,
          sales: 200,
        },
        {
          id: 2,
          name: "AirPods Pro",
          price: 1899,
          image: require("@/assets/images/headphone/airpods-pro.jpg"),
          description: "苹果主动降噪真无线耳机，兼容iOS生态。",
          tags: ["新品", "真无线"],
          stock: 50,
          categoryId: 5,
          sales: 150,
        },
        {
          id: 3,
          name: "Beats Studio Buds",
          image: require("@/assets/images/headphone/beats-studio-buds.jpg"),
          price: 1299,
          description: "时尚潮流，主动降噪，适合运动。",
          tags: ["运动", "真无线"],
          stock: 30,
          categoryId: 5,
          sales: 180,
        },
        {
          id: 4,
          name: "森海塞尔 HD660S",
          price: 3499,
          image: require("@/assets/images/headphone/sennheiser-hd660s.jpg"),
          description: "发烧友级HiFi头戴式耳机，极致音质。",
          tags: ["HiFi", "旗舰"],
          stock: 20,
          categoryId: 2,
          sales: 120,
        },
        {
          id: 5,
          name: "JBL TUNE500BT",
          price: 399,
          image: require("@/assets/images/headphone/jbl-tune500bt.jpg"),
          description: "轻便蓝牙耳机，适合日常通勤。",
          tags: ["蓝牙", "通勤"],
          stock: 80,
          categoryId: 3,
          sales: 160,
        },
        {
          id: 6,
          name: "ATH-M50x",
          price: 1199,
          image: require("@/assets/images/headphone/ath-m50x.jpg"),
          description: "专业录音室监听耳机，经典之选。",
          tags: ["HiFi", "录音室"],
          stock: 40,
          categoryId: 2,
          sales: 90,
        },
        {
          id: 7,
          name: "G PRO X",
          price: 899,
          image: require("@/assets/images/headphone/g-pro-x.jpg"),
          description: "电竞游戏耳机，清晰语音，舒适佩戴。",
          tags: ["游戏", "电竞"],
          stock: 15,
          categoryId: 4,
          sales: 50,
        },
        {
          id: 8,
          name: "FreeBuds Pro",
          price: 1099,
          image: require("@/assets/images/headphone/freebuds-pro.jpg"),
          description: "华为旗舰真无线降噪耳机。",
          tags: ["真无线", "降噪"],
          stock: 25,
          categoryId: 5,
          sales: 140,
        },
      ];
      commit("setFlowers", flowers);
    },
    async login({ commit, state }, credentials) {
      // 模拟API延迟
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // 允许任何账号密码登录
      const user = { username: credentials.username, password: credentials.password };
      commit("setUser", user);
      return Promise.resolve(user);
    },
    async register({ commit, state }, userData) {
      // 模拟API延迟
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // 检查用户名是否已存在
      if (state.users.some((u) => u.username === userData.username)) {
        throw new Error("用户名已存在");
      }

      const newUser = {
        username: userData.username,
        password: userData.password,
      };

      commit("addUser", newUser);
    },
    logout({ commit }) {
      commit("setUser", null);
    },
    // 检查本地存储中的用户信息
    checkAuth({ commit }) {
      return new Promise(resolve => {
        const userStr = localStorage.getItem("user");
        if (userStr) {
          try {
            const user = JSON.parse(userStr);
            commit("setUser", user);
            resolve(true);
          } catch (e) {
            localStorage.removeItem("user");
            resolve(false);
          }
        } else {
          resolve(false);
        }
      });
    },
    // 应用启动时检查并加载购物车数据
    checkCartOnStartup({ commit }) {
      const cartStr = localStorage.getItem("cart");
      if (cartStr) {
        try {
          const cart = JSON.parse(cartStr);
          commit("setCart", cart);
        } catch (e) {
          localStorage.removeItem("cart");
        }
      }
    },
    addOrder({ commit }, order) {
      // 模拟API延迟，实际上这里可以直接commit mutation
      return new Promise(resolve => {
        setTimeout(() => {
          commit("addOrder", order);
          resolve();
        }, 500);
      });
    },
  },
});
